# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         project.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 10:53
# -------------------------------------------------------------------------------
from rest_framework import serializers

from apps.BasicAuthService.serializers import BaseListSerializer, TidyUserSerializer, BaseSerializer
from apps.HttpAutoTestService.models import Project
from apps.HttpAutoTestService.serializers import TidyEnvironmentSerializer

__all__ = ['ProjectNameListSerializer', 'ProjectListSerializer', 'ProjectSerializer', 'TidyProjectSerializer']


class ProjectNameListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('id', 'name', 'global_variables', 'default_environment_id')


class ProjectListSerializer(BaseListSerializer):
    default_environment = TidyEnvironmentSerializer()
    members = TidyUserSerializer(many=True)
    environments = TidyEnvironmentSerializer(many=True)

    class Meta:
        model = Project
        fields = '__all__'


class ProjectSerializer(BaseSerializer):
    def create(self, validated_data):
        environments = validated_data.pop('environments')
        members = validated_data.pop('members')
        validated_data['creator'] = self.context['request'].user
        validated_data['modifier'] = self.context['request'].user
        project = Project.objects.create(**validated_data)
        project.environments.set(environments)
        project.members.set(members)
        return project

    class Meta:
        model = Project
        fields = '__all__'
        extra_kwargs = {
            'members': {'required': False},
            'default_environment': {'required': True}
        }


class TidyProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('id', 'name', 'is_deleted')
